package com.lwlk.zdk.controller.RealTime;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lwlk.zdk.mapper.T.*;
import com.lwlk.zdk.mapper.pw.pwVehiclePathMapper;
import com.lwlk.zdk.service.CarService.CarService;
import com.lwlk.zdk.util.HttpClientUtils;
import com.lwlk.zdk.util.PropUtils;
import com.lwlk.zdk.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@Transactional
@RequestMapping(value = "/realTime")
public class RealTimeController {

    private final static String port = PropUtils.getString("ports");
    private final static String Ip = PropUtils.getString("Ip");
    private final static String clientCode = PropUtils.getString("clientCode");

    @Autowired
    pwVehiclePathMapper pwVehiclePathMapper;
    @Autowired
    TDisVehicleMapper tDisVehicleMapper;
    @Autowired
    TDisPlatformMapper tDisPlatformMapper;
    @Autowired
    TDisEnterpriseMapper tDisEnterpriseMapper;
    @Autowired
    CarService carService;
    @Autowired
    TRegionMapper tRegionMapper;
    @Autowired
    TDisDictionaryMapper tDisDictionaryMapper;

    @ApiOperation(value = "报警明细统计模块")
    @RequestMapping(value = "/alarmStatistics",method = RequestMethod.GET)
    public JSONObject Statistics(String date,String status,String limit,String page,String regionCode,String eId,String vNumber) {
        if (vNumber!=null && vNumber.length() < 3 && !vNumber.equals("")) {
            String list = "{\"code\":1009,\"msg\":\"请输入车牌号不少于3位\"}";
            return JSONObject.parseObject(list);
        }
        String eIdsList="";
        String vIdlist="";
        String pIdList="";
        String vIds=null;

        if (vNumber!=null && vNumber.equals("")==false){
            List<Map> vehicleNumberList=tDisVehicleMapper.selectVehicleId(vNumber.toUpperCase());
            if (vehicleNumberList.size()>0){
                for (int i = 0; i < vehicleNumberList.size(); i++) {
                    vIdlist=vIdlist+vehicleNumberList.get(i).get("vehicle_id")+",";
                }
                vIds=StringUtils.join(vIdlist.split(","),",");
            }else {
                String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
                return JSONObject.parseObject(list);
            }
        }
        Map map=new HashMap();
        map.put("date",date);//必传 查询时间yyyy-MM-dd
        map.put("vIds",vIds);//车辆id，多个英文逗号分隔
        map.put("eIds",eId);//企业id，多个英文逗号分隔
        map.put("status",status);//在线状态
        map.put("limit",limit);//必传 页面记录数,默认值为10
        map.put("page",page);// 必传 页码，默认值为1
        map.put("regionCode",regionCode);// 必填 用户所属行政区划
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/v1/statistics/alarmType/statisticDetails";
        String result= HttpClientUtils.doGet(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONObject jo=json.getJSONObject("result");
        if (jo==null){
            String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
            return JSONObject.parseObject(list);
        }
        JSONArray jsonArray=jo.getJSONArray("list");

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer vId=Integer.parseInt(jsonObject.getString("vId"));//车辆id
            Integer eIds=Integer.parseInt(jsonObject.getString("eId"));//企业id
            String industryId=jsonObject.getString("industryId");//行业id
            Integer admidivcode= Integer.valueOf(jsonObject.getString("admdivcode"));//所属地区
            List<Map<String,Object>>vehicleList=tDisVehicleMapper.selectVehicle(vId);//车辆名称
            String regionName=tRegionMapper.selectAreaCode(admidivcode);
            if (vehicleList.size()==0){
                jsonObject.put("vehicleTypeName",null);
                jsonObject.put("vehicleLicenseColor",null);//车牌颜色
            }else {
                String vehicleType=tDisDictionaryMapper.selectVehicleType(String.valueOf(vehicleList.get(0).get("vehicleType")));//车辆类型
                jsonObject.put("vehicleTypeName",vehicleType);
                jsonObject.put("vehicleLicenseColor",vehicleList.get(0).get("item_name"));//车牌颜色
            }
            String industryName=tDisDictionaryMapper.selectByItemValue(industryId);
            String administrationName=tRegionMapper.selectByoId(admidivcode);
            String aType=jsonObject.getString("alarmType");//报警类型
            String enterpriseName=tDisEnterpriseMapper.selectByEid(eIds);
            String vehicleName=tDisVehicleMapper.selectByVid(vId);
            jsonObject.put("enterpriseName",enterpriseName);
            jsonObject.put("industryName",industryName);
            jsonObject.put("vehicleName",vehicleName);
            jsonObject.put("regionName",regionName);
            jsonObject.put("administrationName",administrationName);
        }
        return json;
    }


    @ApiOperation(value = "报警超时推送模块")
    @RequestMapping(value = "/AlarmTimeout",method = RequestMethod.GET)
    public JSONObject list(String date,String vNumber,String eId,String limit,String page,String regionCode){
        try {
            if (vNumber!=null && vNumber.length() < 3 && !vNumber.equals("")) {
                String list = "{\"code\":1009,\"msg\":\"请输入车牌号不少于3位\"}";
                return JSONObject.parseObject(list);
            }
            String eIdsList="";
            String vIdlist="";
            String vIds=null;
            if (vNumber!=null && vNumber.equals("")==false){
                List<Map> vehicleNumberList=tDisVehicleMapper.selectVehicleId(vNumber.toUpperCase());
                if (vehicleNumberList.size()>0){
                    for (int i = 0; i < vehicleNumberList.size(); i++) {
                        vIdlist=vIdlist+vehicleNumberList.get(i).get("vehicle_id")+",";
                    }
                    vIds=StringUtils.join(vIdlist.split(","),",");
                }else {
                    String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
                    return JSONObject.parseObject(list);
                }
            }
            Map map=new HashMap();
            map.put("date",date);//必选 查询时间yyyy-MM-dd
            map.put("vIds",vIds);//车辆id，多个英文逗号分隔
            map.put("eIds",eId);//企业id，多个英文逗号分隔
            map.put("limit",limit);//必传 页面记录数，默认10
            map.put("page",page);// 必传 页码，默认值为1
            map.put("regionCode",regionCode);
            Set<String> set = map.keySet();
            Iterator<String> it = set.iterator();
            while (it.hasNext()) {
                String str = it.next();
                if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                    map.remove(str);
                    set = map.keySet();
                    it = set.iterator();
                }
            }
            Map<String,String>headMap=new HashMap<>();
            headMap.put("clientCode",clientCode);
            String url="http://"+Ip+":"+port+"/dis/statistics/vehicleAlarm/overtimePush";
            String result=HttpClientUtils.doGet(url,headMap,map);
            JSONObject json= JSONObject.parseObject(result);
            JSONObject jo=json.getJSONObject("result");
            JSONArray jsonArray=jo.getJSONArray("list");
            if (jsonArray==null){
                return json;
            }
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                Integer vId=Integer.parseInt(jsonObject.getString("vId"));//车辆id
                Integer eIds=Integer.parseInt(jsonObject.getString("eId"));//企业id
                String industryId=jsonObject.getString("industryId");//行业id
                String alarmType=jsonObject.getString("alarmType");//报警类型
                String alarmTypeName=tDisDictionaryMapper.selectAlarmType(alarmType);
                String industryName= tDisDictionaryMapper.selectByItemValue(industryId);
                String oId=jsonObject.getString("oId");//机构id
                String administrationName=tRegionMapper.selectByoId(Integer.parseInt(oId));
                String regionName=tRegionMapper.selectAreaCode(Integer.parseInt(oId));
                String enterpriseName=tDisEnterpriseMapper.selectByEid(eIds);//企业名称
                List<Map<String,Object>>vehicleList=tDisVehicleMapper.selectVehicle(vId);//车辆名称
                if (vehicleList.size()==0){
                    jsonObject.put("vehicleType",null);
                    jsonObject.put("vehicleName",null);
                    jsonObject.put("vehicleLicenseColor",null);//车牌颜色
                }else {
                    String vehicleType=tDisDictionaryMapper.selectVehicleType(String.valueOf(vehicleList.get(0).get("vehicle_type")));//车辆类型
                    jsonObject.put("vehicleType",vehicleType);
                    jsonObject.put("vehicleName",vehicleList.get(0).get("vehicle_number"));
                    jsonObject.put("vehicleLicenseColor",vehicleList.get(0).get("item_name"));//车牌颜色
                }
                jsonObject.put("enterpriseName",enterpriseName);
                jsonObject.put("industryName",industryName);
                jsonObject.put("administrationName",administrationName);
                jsonObject.put("regionName",regionName);
                jsonObject.put("alarmType",alarmTypeName);

            }
            return json;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    @ApiOperation(value = "出域车辆")
    @RequestMapping(value = "/TheDomainOfVehicle",method = RequestMethod.POST)
    public JSONObject TheDomainOfVehicle(String industryId,String vNumber,String eName,String admdivcode,String currPage,String pageSize){
        if (vNumber!=null && vNumber.length() < 3 && !vNumber.equals("")) {
            String list = "{\"code\":1009,\"msg\":\"请输入车牌号不少于3位\"}";
            return JSONObject.parseObject(list);
        }
        String eIdsList="";
        String vIdlist="";
        String eIds=null;
        String vIds=null;
        if (eName!=null && eName.equals("")==false){
            List<Map> eIdsLists = tDisEnterpriseMapper.selectEnterpriseNameList(eName);
            if (eIdsLists.size()>0){
                for (int i = 0; i < eIdsLists.size(); i++) {
                    eIdsList = eIdsList + eIdsLists.get(i).get("enterprise_id")+",";
                }
                eIds=StringUtils.join(eIdsList.split(","),",");
            }else {
                String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
                return JSONObject.parseObject(list);
            }
        }
        if (vNumber!=null && vNumber.equals("")==false){
            List<Map> vehicleNumberList=tDisVehicleMapper.selectVehicleId(vNumber.toUpperCase());
            if (vehicleNumberList.size()>0){
                for (int i = 0; i < vehicleNumberList.size(); i++) {
                    vIdlist=vIdlist+vehicleNumberList.get(i).get("vehicle_id")+",";
                }
                vIds=StringUtils.join(vIdlist.split(","),",");
            }else {
                String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
                return JSONObject.parseObject(list);
            }
        }
        Map map=new HashMap();
        map.put("industryId",industryId);//行业编码
        map.put("vid",vIds);//车辆ID
        map.put("eid",eIds);//企业ID
        map.put("admdivcode",admdivcode);//必传 地区编码
        map.put("currPage",currPage);//必传 页码
        map.put("pageSize",pageSize);//必传 页数
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/statistic/InOrOut/out";
        String result=HttpClientUtils.doPost(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONObject jo=json.getJSONObject("result");
        if (jo==null){
            return json;
        }
        JSONArray jsonArray=jo.getJSONArray("list");

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer vId=Integer.parseInt(jsonObject.getString("vid"));//车辆id
            Integer eId=Integer.parseInt(jsonObject.getString("eid"));//企业id
            String enterpriseName=tDisEnterpriseMapper.selectByEid(eId);
            jsonObject.put("enterpriseName",enterpriseName);
        }
        return json;
    }


    @ApiOperation(value = "入域车辆")
    @RequestMapping(value = "/InTheDomainOfVehicle",method = RequestMethod.POST)
    public JSONObject InTheDomainOfVehicle(String industryId,String admdivcode,String currPage,String pageSize,String eName,String vNumber){
        if (vNumber!=null && vNumber.length() < 3 && !vNumber.equals("")) {
            String list = "{\"code\":1009,\"msg\":\"请输入车牌号不少于3位\"}";
            return JSONObject.parseObject(list);
        }
        String eIdsList="";
        String vIdlist="";
        String eIds=null;
        String vIds=null;
        if (eName!=null && eName.equals("")==false){
            List<Map> eIdsLists = tDisEnterpriseMapper.selectEnterpriseNameList(eName);
            if (eIdsLists.size()>0){
                for (int i = 0; i < eIdsLists.size(); i++) {
                    eIdsList = eIdsList + eIdsLists.get(i).get("enterprise_id")+",";
                }
                eIds=StringUtils.join(eIdsList.split(","),",");
            }else {
                String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
                return JSONObject.parseObject(list);
            }
        }
        if (vNumber!=null && vNumber.equals("")==false){
            List<Map> vehicleNumberList=tDisVehicleMapper.selectVehicleId(vNumber);
            if (vehicleNumberList.size()>0){
                for (int i = 0; i < vehicleNumberList.size(); i++) {
                    vIdlist=vIdlist+vehicleNumberList.get(i).get("vehicle_id")+",";
                }
                vIds=StringUtils.join(vIdlist.split(","),",");
            }else {
                String list="{\"code\":1001,\"msg\":\"接口执行成功\",\"result\":{\"currPage\":1,\"list\":[],\"pageSize\":0,\"totalCount\":0,\"totalPage\":0}}";
                return JSONObject.parseObject(list);
            }
        }
        Map map=new HashMap();
        map.put("industryId",industryId);//行业编码
        map.put("vid",vIds);//车辆ID
        map.put("eid",eIds);//企业ID
        map.put("admdivcode",admdivcode);//地区编码
        map.put("currPage",currPage);//必传 页码
        map.put("pageSize",pageSize);//必传 页数
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            if(map.get(str)==null || map.get(str) =="null"|| map.get(str)==""){
                map.remove(str);
                set = map.keySet();
                it = set.iterator();
            }
        }
        Map<String,String>headMap=new HashMap<>();
        headMap.put("clientCode",clientCode);
        String url="http://"+Ip+":"+port+"/dis/statistic/InOrOut/in";
        String result=HttpClientUtils.doPost(url,headMap,map);
        JSONObject json= JSONObject.parseObject(result);
        JSONObject jo=json.getJSONObject("result");
        JSONArray jsonArray=jo.getJSONArray("list");
        if (jsonArray==null){
            return json;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Integer vId=Integer.parseInt(jsonObject.getString("vid"));//车辆id
            Integer eId=Integer.parseInt(jsonObject.getString("eid"));//企业id
            String oId=jsonObject.getString("admdivcode");//机构id
            String areaCode=tRegionMapper.selectByoId(Integer.valueOf(oId));
            String enterpriseName=tDisEnterpriseMapper.selectByEid(eId);
            String vehicleName=tDisVehicleMapper.selectByVid(vId);
            jsonObject.put("enterpriseName",enterpriseName);
            jsonObject.put("vehicleName",vehicleName);
            jsonObject.put("administrationName",areaCode);

        }
        return json;
    }


}
